import 'package:flutter/material.dart';
import 'package:vmall_app/models/goods.dart';
import 'package:vmall_app/widgets/plus_sub.dart';

class ChoiceGoods extends StatefulWidget {
  final int goodsId;
  final Function close;
  final Size size;

  ChoiceGoods({Key key, this.goodsId, this.close, this.size}) : super(key: key);

  @override
  _ChoiceGoodsState createState() => _ChoiceGoodsState();
}

class _ChoiceGoodsState extends State<ChoiceGoods>
    with TickerProviderStateMixin {
  bool isExpanded = false;
  int selectedIndex;
  Spec spec;
  GoodsSummary goodsSummary;
  Goods goods;

  AnimationController animationController;
  PageController pageController;

  Animation<double> imageLeftAnimation;
  Animation<double> imageHeightAimation;
  Animation<double> imageWidthAimation;
  Animation<double> containerAimation;
  Animation<double> infoTopAnimation;
  Animation<double> priceLeftAnimation;
  Animation<double> stockLeftAnimation;
  Animation<double> descriptionLeftAnimation;

  GlobalKey priceGlobalKey = GlobalKey();
  GlobalKey stockGlobalKey = GlobalKey();
  GlobalKey descriptionGlobalKey = GlobalKey();

  double startPriceLeft;
  double startStockLeft;
  double startDescriptionLeft;

  bool isSelected = false;
  bool isUsePageView = false;
  bool pointerUp = false;
  @override
  void initState() {
    pageController = PageController(viewportFraction: 0.4);
    this.pointerUp = false;
    initGoodsImageAndInfoAnimation();
    initGoods();
    super.initState();
  }

  initGoods() {
    goods = getGoodsById(this.widget.goodsId);
    goodsSummary = goods.getSummery();
  }

  initGoodsImageAndInfoAnimation() {
    this.isExpanded = false;
    animationController =
        AnimationController(vsync: this, duration: Duration(milliseconds: 1000));

    animationController.addListener(() {
      setState(() {});
    });

    animationController.addStatusListener((status) {
      //展开动画完成，如果没有选择商品，则显示多个商品的滑动列表
      if (status == AnimationStatus.completed && selectedIndex == null) {
        this.isUsePageView = true;
        print('ok');
      } else {
        //this.isUsePageView = false;
      }
    });

    var containterHeight = this.widget.size.height * 0.56;
    var imageHeight = containterHeight * 0.7;
    var imageWidth = imageHeight * 3 / 4;

    var imageLeft = (this.widget.size.width - imageHeight * 3 / 4) / 2;
    startPriceLeft = startStockLeft = startDescriptionLeft = 120;
    imageLeftAnimation =
        Tween<double>(begin: 10, end: imageLeft).animate(animationController);
    imageHeightAimation = Tween<double>(begin: 100, end: imageHeight)
        .animate(animationController);
    imageWidthAimation =
        Tween<double>(begin: 100, end: imageWidth).animate(animationController);
    containerAimation = Tween<double>(begin: 120, end: containterHeight)
        .animate(animationController);
    infoTopAnimation = Tween<double>(begin: 30, end: imageHeight + 10)
        .animate(animationController);
    priceLeftAnimation = stockLeftAnimation = descriptionLeftAnimation =
        Tween<double>(begin: startPriceLeft, end: 130)
            .animate(animationController);
  }

  @override
  void dispose() {
    animationController.dispose();
    pageController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    if (selectedIndex != null) {
      spec = goods.specs[this.selectedIndex];
    }
    return Container(
        decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.only(
                topLeft: Radius.circular(10), topRight: Radius.circular(10))),
        child: Stack(
          children: <Widget>[
            Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: <Widget>[
                Padding(
                  padding: const EdgeInsets.all(0.0),
                  child: Container(
                    height: containerAimation.value,
                    width: this.widget.size.width,
                    child: Stack(
                      children: <Widget>[
                        this.isUsePageView
                            ? Positioned(
                                top: 10,
                                left: 0,
                                right:0,
                                child: Container(
                                  width:imageWidthAimation.value,
                                  height: imageHeightAimation.value,
                                  child: PageView.builder(
                                    controller: pageController,
                                    itemCount: goodsSummary.imageUrls.length,
                                    itemBuilder: (context, index) {
                                      return Container(
                                        decoration: BoxDecoration(
                                          color: Colors.white,
                                          borderRadius:
                                              BorderRadius.circular(10),
                                        ),
                                        padding: const EdgeInsets.all(0),
                                        width: imageWidthAimation.value,
                                        height:imageHeightAimation.value,
                                        child: ClipRRect(
                                          borderRadius:
                                              BorderRadius.circular(10),
                                          child: Image.network(
                                            goodsSummary.imageUrls[index],
                                            fit: BoxFit.fitWidth,
                                          ),
                                        ),
                                      );
                                    },
                                  ),
                                ),
                              )
                            : Positioned(
                                top: 10,
                                left: imageLeftAnimation.value,
                                child: Container(
                                  decoration: BoxDecoration(
                                    color: Colors.white,
                                    borderRadius: BorderRadius.circular(10),
                                  ),
                                  padding: const EdgeInsets.all(0),
                                  width: imageWidthAimation.value,
                                  height: imageHeightAimation.value,
                                  child: ClipRRect(
                                    borderRadius: BorderRadius.circular(10),
                                    child: Image.network(
                                      spec != null
                                          ? spec.imageUrls[0]
                                          : goodsSummary.imageUrls[0],
                                      fit: BoxFit.fitWidth,
                                    ),
                                  ),
                                ),
                              ),
                        this.isSelected
                            ? Positioned(
                                top: infoTopAnimation.value,
                                left: 0,
                                right: 0,
                                child: Center(
                                  child: Text(
                                    spec == null
                                        ? goodsSummary.description
                                        : '¥${spec.price} 券后 ¥${spec.useCouponPrice ?? 0}',
                                    key: priceGlobalKey,
                                    style: TextStyle(
                                        fontSize: 12,
                                        color: Colors.red,
                                        fontWeight: FontWeight.w300),
                                  ),
                                ),
                              )
                            : Positioned(
                                top: infoTopAnimation.value,
                                left: priceLeftAnimation.value,
                                child: Text(
                                  spec == null
                                      ? goodsSummary.description
                                      : '¥${spec.price} 券后 ¥${spec.useCouponPrice ?? 0}',
                                  key: priceGlobalKey,
                                  style: TextStyle(
                                      fontSize: 12,
                                      color: Colors.red,
                                      fontWeight: FontWeight.w300),
                                ),
                              ),
                        this.isSelected
                            ? Positioned(
                                top: infoTopAnimation.value + 20,
                                left: 0,
                                right: 0,
                                child: Center(
                                  child: Text(
                                      spec == null
                                          ? "库存${goodsSummary.stockCount}${goods.unitName}"
                                          : "库存${spec.stockCount}${goods.unitName}",
                                      style: TextStyle(
                                          color: Colors.grey, fontSize: 10),
                                      key: stockGlobalKey),
                                ),
                              )
                            : Positioned(
                                top: infoTopAnimation.value + 20,
                                left: stockLeftAnimation.value,
                                child: Text(
                                    spec == null
                                        ? "库存${goodsSummary.stockCount}${goods.unitName}"
                                        : "库存${spec.stockCount}${goods.unitName}",
                                    style: TextStyle(
                                        color: Colors.grey, fontSize: 10),
                                    key: stockGlobalKey),
                              ),
                        this.isSelected
                            ? Positioned(
                                top: infoTopAnimation.value + 40,
                                left: 0,
                                right: 0,
                                child: Center(
                                  child: Text(
                                      spec == null
                                          ? "配送至：鄞州区"
                                          : '配送至：鄞州区，已选："${spec.description}"',
                                      style: TextStyle(fontSize: 10),
                                      key: descriptionGlobalKey),
                                ),
                              )
                            : Positioned(
                                top: infoTopAnimation.value + 40,
                                left: descriptionLeftAnimation.value,
                                child: Text(
                                    spec == null
                                        ? "配送至：鄞州区"
                                        : '配送至：鄞州区，已选："${spec.description}"',
                                    style: TextStyle(fontSize: 10),
                                    key: descriptionGlobalKey),
                              ),
                        Positioned(
                          top: 10,
                          right: 10,
                          child: GestureDetector(
                            onTap: () {
                              if (this.widget.close != null) {
                                this.widget.close();
                                print('close');
                              }
                            },
                            child: Container(
                              height: 20,
                              width: 20,
                              child: Icon(
                                Icons.cancel,
                                color: Colors.grey,
                                size: 20,
                              ),
                            ),
                          ),
                        ),
                      ],
                    ),
                  ),
                ),
                Divider(),
                Expanded(
                    child: NotificationListener(
                  onNotification: (notification) {
                    if (notification is ScrollUpdateNotification) {
                      if (notification.metrics.pixels < -20 && this.pointerUp) {
                        descriptionLeftAnimation = Tween<double>(
                                begin: startDescriptionLeft,
                                end: (this.widget.size.width -
                                        descriptionGlobalKey
                                            .currentContext.size.width) /
                                    2)
                            .animate(animationController);
                        stockLeftAnimation = Tween<double>(
                                begin: startStockLeft,
                                end: (this.widget.size.width -
                                        stockGlobalKey
                                            .currentContext.size.width) /
                                    2)
                            .animate(animationController);
                        priceLeftAnimation = Tween<double>(
                                begin: startPriceLeft,
                                end: (this.widget.size.width -
                                        priceGlobalKey
                                            .currentContext.size.width) /
                                    2)
                            .animate(animationController);
                        animationController.forward();
                        isSelected = false;
                        this.isExpanded = true;
                      } else if (notification.metrics.pixels > 10) {
                        this.pointerUp = false;
                        animationController.reverse();
                        this.isExpanded = false;
                        isSelected = false;
                        this.isUsePageView = false;
                      }
                    }
                    return true;
                  },
                  child: Padding(
                    padding: const EdgeInsets.all(10.0),
                    child: Listener(
                      onPointerUp: (event){
                         this.pointerUp = true;
                      },
                      child: ListView(
                        physics: AlwaysScrollableScrollPhysics(
                            parent: BouncingScrollPhysics()),
                        children: <Widget>[
                          Text('选择配送区域'),
                          Divider(),
                          Text(
                            '选择分类',
                            style: TextStyle(fontSize: 12),
                          ),
                          Wrap(
                            direction: Axis.horizontal,
                            children: <Widget>[
                              for (var i = 0; i < goods.specs?.length; i++)
                                GestureDetector(
                                  onTap: () {
                                    this.selectedIndex = i;
                                    this.spec = goods.specs[i];
                                    //計算新的位置left
                                    if (this.isExpanded) {
                                      isSelected = true;
                                    }
                                    this.isUsePageView = false;
                                    setState(() {});
                                  },
                                  child: Container(
                                    decoration: this.selectedIndex == i
                                        ? BoxDecoration(
                                            color:
                                                Colors.orange.withOpacity(0.1),
                                            borderRadius:
                                                BorderRadius.circular(3),
                                            border: Border.all(
                                                color: Colors.red, width: 0.5))
                                        : BoxDecoration(
                                            color: Colors.grey.withOpacity(0.1),
                                            borderRadius:
                                                BorderRadius.circular(3),
                                          ),
                                    margin: const EdgeInsets.all(5),
                                    padding: const EdgeInsets.all(2),
                                    height: 25,
                                    width: 120,
                                    child: Row(
                                      children: <Widget>[
                                        Image.network(
                                            goods.specs[i].imageUrls[0]),
                                        Padding(
                                          padding: const EdgeInsets.only(
                                              left: 5,
                                              top: 5,
                                              right: 5,
                                              bottom: 5),
                                          child: Text(
                                            goods.specs[i].description,
                                            style: this.selectedIndex == i
                                                ? TextStyle(
                                                    fontSize: 10,
                                                    color: Colors.red)
                                                : TextStyle(
                                                    fontSize: 10,
                                                    color: Colors.black),
                                          ),
                                        )
                                      ],
                                    ),
                                  ),
                                )
                            ],
                          ),
                          Divider(),
                          Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: <Widget>[
                              Text(
                                '购买数量',
                                style: TextStyle(fontSize: 12),
                              ),
                              PlusSub()
                            ],
                          )
                        ],
                      ),
                    ),
                  ),
                )),
              ],
            ),
          ],
        ));
  }
}
